package com.shenfc.fxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shenfc.fxzj.constants.RoleTypeEnum;
import com.shenfc.fxzj.domain.PageBean;
import com.shenfc.fxzj.domain.SysRoleRel;
import com.shenfc.fxzj.domain.SysUser;
import com.shenfc.fxzj.mapper.SysRoleRelMapper;
import com.shenfc.fxzj.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.shenfc.fxzj.service.ISysUserService;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/2/3 0003.
 */
@Service("sysUserService")
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleRelMapper sysRoleRelMapper;

    @Override
    public SysUser getSysUserByUserName(String userName) {
        return sysUserMapper.getSysUserByUserName(userName);
    }

    @Override
    public PageInfo<SysUser> querySysUserPage(Map<String, Object> map, PageBean pageBean) {
        PageHelper.startPage(pageBean.getPage(), pageBean.getLimit());
        List<SysUser> list = sysUserMapper.querySysUserList(map);

        PageInfo<SysUser> pageInfo = new PageInfo<SysUser>(list);
        pageBean.setRecTotal(pageInfo.getTotal());
        return pageInfo;
    }

    @Override
    public void updateStatus(Long id, String status) {
        SysUser sysUser = new SysUser();
        sysUser.setId(id);
        sysUser.setStatus(status);
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public SysUser getSysUserById(Long id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void addSysUser(SysUser sysUser) {
        sysUserMapper.insertSelective(sysUser);
        addSysRoleRel(sysUser);
    }

    @Override
    @Transactional
    public void updateSysUser(SysUser sysUser) {
        sysRoleRelMapper.deleteByObjId(sysUser.getId(),RoleTypeEnum.USER.getKey());
        addSysRoleRel(sysUser);
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    public void addSysRoleRel(SysUser sysUser){
        SysRoleRel sysRoleRel = new SysRoleRel();
        sysRoleRel.setRoleId(sysUser.getRoleId());
        sysRoleRel.setRelType(RoleTypeEnum.USER.getKey());
        sysRoleRel.setObjId(sysUser.getId());
        sysRoleRelMapper.insertSelective(sysRoleRel);
    }

    @Override
    public List<SysUser> getSysUsersByRoleId(Long roleId) {
        return sysUserMapper.getSysUsersByRoleId(roleId);
    }
}
